define(function(require){
    $(function(){
    	/*---------- 算法管理——管理员 ----------*/
    	/*算法前后台函数对接：create(新建)、update(修改)、delete(删除)、get(获取算法信息)、change_status(切换算法状态)、copy_that(复制算法)
    	算法前后台对接参数：id(算法id)、name(算法名称)、code(代码)、xml_format(xml格式)、status(算法状态)、passed(是否测试通过)*/
        /* 表格 */
    	var bodyTemplate = ['<tr algorithm_id="{id}">',
	    	                    '<td class="txtc">{name}</td>',
	    	                    '<td class="txtc">{status}</td>',
	    	                    '<td class="txtc">{time}</td>',
	    	                    '<td class="txtc passed">{passed}</td>',
	    	                    '<td class="txtc">',
	    	                    	'<a class="ibtn viewbtn" style="display:{view}" href="javascript:;" title="查看"><span class="glyphicon glyphicon-eye-open"></span></a>',
		                     		'<a class="ibtn editbtn" style="display:{edit}" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
		                     		'<a class="ibtn copybtn" href="javascript:;" title="复制"><span class="glyphicon glyphicon-floppy-save"></span></a>',
		                     		'<a class="ibtn delbtn {del}" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',
		                     		'<a class="ibtn publicbtn" style="display:{pub}" href="javascript:;" title="发布"><span class="glyphicon glyphicon-share-alt"></span></a>',
		                     		'<a class="ibtn abandonbtn {idsabandon}" style="display:{abandon}" href="javascript:;" title="废弃"><span class="glyphicon glyphicon-trash"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');

    	var grid = Grid.init({
	            holder:'algorithmList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/algorithm/get_list',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
    	//passed,0代表没通过，1代表通过
    	//status 0,1,2，代表：未发布、发布、废弃
    	grid.modifyModel(function(data){
    		data.del = ''
    		data.idsabandon = ''
        	if(data.status == 0){
        		data.status = '<span class="label label-default" style="font-size:14px;">未发布</span>';
        		data.edit = 'inline';
        		data.view = 'none';
        		data.pub = 'inline';
        		data.abandon = 'none';
        	}else if(data.status == 1){
        		data.status = '<span class="label label-success" style="font-size:14px;">已发布</span>';
        		data.edit = 'none';
        		data.view = 'inline';
        		data.pub = 'none';
        		data.abandon = 'inline';
        		data.del = 'disabled'
        	}else{
        		data.status = '<span class="label label-warning" style="font-size:14px;">已废弃</span>';
        		data.edit = 'none';
        		data.view = 'inline';
        		data.pub = 'none';
        		data.abandon = 'inline';
        		data.del = 'disabled'
        		data.idsabandon = 'disabled'
        	}
        	if(data.passed == 1){
        		data.passed = '<span class="label label-success" style="font-size:14px;">已通过</span>';
        	}else{
        		data.passed = '<span class="label label-default" style="font-size:14px;">未通过</span>';
        	}
        	data.time = data.time.replace('T',' ');
    	});
    	grid.onfilled(function(data){
     		grid.data = data;
     		$('.ibtn').tooltip();
     	});
    	
        /* 数据搜索 */
        var filterData = function(pno){
        	var txt = $('.pageheader .searchbox-ipt').val(),
        		status = $('.pageheader [name=status]').val(),
        		passed = $('.pageheader [name=passed]').val(),
            	pageSize = 20;
        	
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
        		search_text: txt,
        		status: status,
        		passed: passed,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        //按名称模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        //按算法状态搜索
        $('.pageheader [name=status]').select2().on('change', function(){
        	filterData();
        });
        
        //按测试结果搜索
        $('.pageheader [name=passed]').select2().on('change', function(){
        	filterData();
        });
        
        /* 新建+修改+复制+查看算法 */
        $(document).on('click', '.createalgorithm, .editbtn, .copybtn, .viewbtn', function(){
        	var $this = $(this), isEdit = false, isCopy = false, isView = false, title = '新建';
        	if($this.hasClass('editbtn')){
        		isEdit = true;
        		title = '修改';
        	}
        	if($this.hasClass('copybtn')){
        		isCopy = true;
        		title = '复制';
        	}
        	if($this.hasClass('viewbtn')){
        		isView = true;
        		title = '查看';
        	}
        	$ajax.ajax({
        		url: '/static/trp/template/popalgorithm.html',
        		success: function(html){
        			var dlgOp = {
        				title: title+'算法',
        				width: 800,
        				onshow: function(){
        					var $dlg = this, $node = $(this.node),
        						initDlg = function($code){
            						var $uiCode = $('.uicode textarea',$node),
    	        						$javaCode = $('.javacode textarea',$node),
    	        						uiEditor = javaEditor = null;
            						
            						setTimeout(function(){
            							uiEditor = CodeMirror.fromTextArea($uiCode[0],{
    	        							lineNumbers: true,
    	        							styleActiveLine: true,
    	        					        matchBrackets: true,
    	        					        autoCloseTags: true,
    	        					        mode: "htmlmixed"
	        							});
    	        						javaEditor = CodeMirror.fromTextArea($javaCode[0],{
    	        							lineNumbers: true,
    	        							styleActiveLine: true,
    	        					        matchBrackets: true,
    	        					        mode: "text/x-java"
	        							});
    	        						uiEditor.on('change', function(){
    	        							$('.label-success',$node).hide();
        									$('.label-default',$node).show();
    	        						});
    	        						javaEditor.on('change', function(){
    	        							$('.label-success',$node).hide();
        									$('.label-default',$node).show();
    	        						});
            							$('.uicode textarea',$node).removeAttr('disabled').data('editor',uiEditor);
            							$('.javacode textarea',$node).removeAttr('disabled').data('editor',javaEditor);
            							/*$('[name=theme]',$node).on('change', function(){
            								var _theme = $(this).val();
            								$code.theme(uiEditor, _theme);
            								$code.theme(javaEditor, _theme);
            							});*/
            						}, 250);
            						
            						if(isView){
    		        					$('[name=name]',$node).attr('readonly','readonly');
    		        					$('.label-success',$node).removeClass('btn-validation');
    		        				}
    	        					
            						require.async('./common/formatxml', function($format){
            							window.$format = $format;
            							/* 快捷添加 */
            							$('.btn-shortcuts',$node).on('click', function(){
            								var $this = $(this), ctype = $this.attr('ctype'), itype = $this.attr('itype')/*, txt = uiEditor.getValue()*/;
            								uiEditor.replaceSelection($format.gettmpl(ctype, itype));
            							});
            							/*$('.btn-formatxml',$node).on('click', function(){
            								var txt = uiEditor.getValue();
            								uiEditor.setValue($format.format(txt));
            							});*/
            							/* 预览 */
            							$('.btn-preview',$node).on('click', function(){
    	        							var $this = $(this), 
    	        								ctype = $this.attr('ctype'),
    	        								tmpl = '';
    	        							
    	        							$dialog({
    	        								title: '算法预览',
    	        								content: tmpl,
    	        								width: 800,
    	                        				zIndex: semi.utils.topIndex(),
    	        								onshow: function(){
    	        									var _$dlg = this; _$node = $(this.node); 
    	        									if(ctype == 'ui'){
    	    	        								tmpl = $format.gethtml(uiEditor.getValue())
    	    	        								if(semi.utils.isEmpty(tmpl)){
    	    	        									_$dlg.close().remove();
    	    	        									$dialog.alert('未找到节点信息！','warning');
    	    	        									return;
    	    	        								}
    	    	        								_$dlg.content('<div class="UICont"><div class="uicontent">'+tmpl+'</div></div>');
    	    	        								_$dlg.title('算法UI预览');
    	    	        								$format.inithtml();
    	    	        							}else{
    	    	        								var _json = $format.getjson(uiEditor.getValue()), _strjson = [];
    	    	        								//格式化json
    	    	        								$.each(_json, function(key,val){
    	    	        									var _tmpJson = JSON.stringify(semi.utils.newObj(key, val));
    	    	        									_tmpJson = _tmpJson.substring(0,_tmpJson.length-1).substring(1,_tmpJson.length-1);
    	    	        									if($.isArray(val)){
    	    	        										_strjson.push(_tmpJson);
    	    	        									}else{
    	    	        										_strjson.push(_tmpJson.replaceAll(',"', ',\n	"'));
    	    	        									}
    	    	        								});
    	    	        								_json = '{\n	'+_strjson.join(',\n	')+'\n}';
    	    	        								tmpl = '<textarea class="previewjson" style="width:400px;height:300px;" disabled="disabled">'+_json+'</textarea>';
    	    	        								_$dlg.content('<div style="min-width:500px;">'+tmpl+'</div>');
    	    	        								_$dlg.title('算法JSON预览');
    	    	        								setTimeout(function(){
    	    	        									jsonEditor = CodeMirror.fromTextArea($('.previewjson',_$node)[0],{
            	        	        							lineNumbers: true,
            	        	        					        matchBrackets: true,
            	        	        					        mode: "htmlmixed"
            	    	        							});
    	    	        									$('.previewjson',_$node).removeAttr('disabled');
    	    	                						}, 250);
    	    	        							}
    	        									_$node.initUI();	
    	        								}
    	        							}).showModal();
    	        						});
    	        					});
    	        					
    	        					/* 算法检验 */
    	        					$('.btn-validation',$node).on('click', function(){
    	        						require.async('./common/validalgorithm', function($valid){
    	        							$valid.valid({
    	        								xml: uiEditor.getValue(),
    	        								java: javaEditor.getValue(),
    	        								success: function(){
    	        									$('.label-success',$node).show();
    	        									$('.label-default',$node).hide();
    	        								},
    	        								error: function(){
    	        									$('.label-success',$node).hide();
    	        									$('.label-default',$node).show();
    	        								}
    	        							});
    	        						});
    	        					});
        						};
    						require.async('codemirror', function($code){
    							$code.load(['html', 'java'], function(){
    								if(isEdit || isCopy || isView){
        								var id = $this.parents('tr').attr('algorithm_id');
                		        		$ajax.ajax({
                		        			url: '/trp/algorithm/get/',
                		        			data: JSON.stringify({
                		        				id: id
                		        			}),
                		            		contentType : "application/json",
                		                    type : 'POST',
                		                    dataType : 'json',
                		        			success: function(data){
                		        				//{"status": 0, "xml_format": "123123", "code": "123123123", "name": "123123123", "passed": 0, "statusCode": 200}
                		        				$dlg.content(html);
                		        				$('[name=id]',$node).val(id);
                		        				if(isEdit || isView)$('[name=name]',$node).val(data.name);
                		        				$('.uicode textarea',$node).val(decodeURIComponent(data.xml_format));
                		        				$('.javacode textarea',$node).val(decodeURIComponent(data.code));
                		        				if(data.passed==1){
                		        					$('.label-success',$node).show();
                		        					$('.label-default',$node).hide();
                		        				}
            		        					initDlg($code);
                		        			}
                		        		});
                		        	}else{
                		        		$dlg.content(html);
                		        		initDlg($code);
                		        	}
    							});
    						});
        				}
        			}
        			if(!isView){
        				$.extend(dlgOp, {
            				okValue: '确定',
            				ok: function(){
            					var $dlg = this, $node = $(this.node), passed = 0, data = {}, url = '';
            					require('validate');
            					if(!$('form',$node).valid())return false;
            					if($('.label-success',$node).is(':visible')){
            						passed = 1;
    	        				}
            					url = '/trp/algorithm/create/';
            					data = {
        	        				name: $('[name=name]',$node).val(),
        	        				xml_format: encodeURIComponent($('.uicode textarea',$node).data('editor').getValue()),
        	        				code: encodeURIComponent($('.javacode textarea',$node).data('editor').getValue()),
        	        				passed: passed,//0代表没通过，1代表通过
        	        				status: 0	//0,1,2，代表：未发布、发布、废弃
        	        			}
            					if(isEdit){
            						url = '/trp/algorithm/update/';
            						$.extend(data, {
            							id: $('[name=id]',$node).val()
            						});
            					}
            					$ajax.ajax({
            	        			url: url,
            	        			data: JSON.stringify(data),
            	            		contentType : "application/json",
            	                    type : 'POST',
            	                    dataType : 'json',
            	        			success: function(data){
            	    					$dlg.close().remove();
            	    					$dialog.alert(title+'算法成功！','success');
            	    					if(!isEdit){
            	    						filterData();
            	    					}else{
            	    						filterData(semi.utils.gridPage(grid));
            	    					}
            	        			},
            	        			error: function(data){
            	        				var message = title+'算法失败';
            	        				if(!semi.utils.isEmpty(data) && !semi.utils.isEmpty(data.message))message += ('：<b>'+data.message+'</b>');
            	        				$dialog.alert(message+'，请稍后重试！','warning');
            	        			}
            	        		});
            	            	return false;
            				},
            				cancelValue: '取消',
            				cancel: true
        				});
        			}else{
        				$.extend(dlgOp, {
            				cancelValue: '关闭',
            				cancel: true
        				});
        			}
        			$dialog(dlgOp).showModal();
        		}
        	});
        });
        
        /* 删除算法-dialog */
        $(document).on('click', '.delbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), algorithm_id = $tr.attr('algorithm_id');
        	if($this.hasClass('disabled'))return;
        	var $dlg = $dialog.confirm({
        		title: '删除算法',
                content: '您确定要删除该算法吗？',
                ok: function(){
                	var $dlg = this;
                	$ajax.ajax({
                    	url: '/trp/algorithm/delete/',
                    	data: JSON.stringify({
                        	id: $dlg.algorithm_id
        				}),
	            		contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('删除算法成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        }
                    });
                	return false;
                }
        	});
        	$.extend($dlg,{algorithm_id:algorithm_id});
        	
        });
        
        /* 发布+废弃算法-dialog */
        $(document).on('click', '.publicbtn,.abandonbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), algorithm_id = $tr.attr('algorithm_id'), title = '发布';
        	if($('.passed',$tr).text()=='未通过'){
        		$dialog({
		        	title: '提醒',
		            id: 'Alert',
		            fixed: true,
		            time: 3000,
		            padding: '15px 30px',
		            content: '<span class="alert-warning"></span><span>该算法未做算法校验，暂不能发布！<a class="ibtn" style="font-size:12px;" href="javascript:;" title="去校验">去校验</a></span>',
		            onshow: function(){
		            	var $dlg = this, $node = $(this.node);
		            	$('.ibtn',$node).on('click', function(){
		            		$dlg.close().remove();
		            		$('.editbtn',$tr).click();
		            	});
		            },
		            okValue: '知道了',
		            ok: true
		        }).show();
        		return;
        	}
        	if($this.hasClass('abandonbtn'))title = '废弃';
        	if($this.hasClass('disabled'))return;
        	var $dlg = $dialog.confirm({
        		title: title+'算法',
                content: '您确定要'+title+'该算法吗？',
                ok: function(){
                	var $dlg = this;
                	$ajax.ajax({
                    	url: '/trp/algorithm/change_status/',
                    	data: JSON.stringify({
                        	id: $dlg.algorithm_id
        				}),
	            		contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert(title+'算法成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        }
                    });
                	return false;
                }
        	});
        	$.extend($dlg,{algorithm_id:algorithm_id});
        	
        });
        
    });
});